/*
 * @Author: aum
 * @Date: 2021-03-03 15:24:23
 * @LastEditTime: 2021-08-27 18:51:23
 * @LastEditors: aum
 * @Description: axios的拦截等设置
 * @FilePath: \vue3-hand-vant\src\utils\http\Interceptors.ts
 */

import axios, { AxiosResponse, AxiosError } from 'axios'
import { Toast } from 'vant'

export class Interceptors {
  public instance

  public constructor() {
    // 创建axios实例
    this.instance = axios.create({
      baseURL: '/api/',
      withCredentials: true,
      timeout: 1000 * 12
    })
    // 初始化拦截器
    this.initInterceptors()
  }
  // 为了让http.ts中获取初始化好的axios实例
  public getInterceptors() {
    return this.instance
  }
  // 初始化拦截器
  public initInterceptors() {
    // 设置post请求头
    this.instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

    // 响应拦截器
    this.instance.interceptors.response.use(
      // 请求成功
      (res: AxiosResponse<any>) => {
        console.log(res,42);
        
        if (res.status === 200) {
        
          return Promise.resolve(res.data)
        } else {
          Toast({
            message:  '请稍后再试',
            forbidClick: true
          })
          return Promise.resolve(res)
        }
      },
      (error: AxiosError) => {
        console.log(error)
        Promise.resolve({ res: false })
      }
    )
  }
}
